<?php
namespace App\Http\Controllers\Api;

use App\Exports\MemberTalentsExport;
use App\Http\Controllers\Controller;
use App\Imports\MemberTalentsImports;
use App\Models\Member;
use App\Models\MemberTalents;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class AdminTalentsInfoController extends Controller
{
    protected $memberTalentsModel;

    public function __construct()
    {
        $this->memberTalentsModel = new MemberTalents();
    }

    public function list(Request $request)
    {
        if(!$request->has('page_size'))
            return response()->json(['code'=>'0','message'=>'请上传页面条数']);

        if (!$request->has('is_check')) {
            return response()->json(['code' => '0', 'message' => '请上传列表类型']);
        }
        $member = $this->memberTalentsModel->getMemberListTalents($request->input());
        return response()->json(['code' => '1', 'message' => '请求成功', 'data' => $member]);
    }

    /**
     * 审核
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkTalents(Request $request)
    {
        $data = $request->input();
        $bool_data = $this->getValidator($data);
        if ($bool_data['code'] == 0) {
            return response()->json(['code' => '0', 'message' => $bool_data['message']]);
        }

        $bool = $this->memberTalentsModel->updTalents($data['uid'], $bool_data['data']);
        if ($bool['code'] == 1) {
            $message = new MessageController();
            if($bool_data['data']['is_check'] == 1){
                $message->addMessage($data['uid'],'10','您的人才信息注册申请已通过审核');
            }elseif ($bool_data['data']['is_check'] == 3){
                $message->addMessage($data['uid'],'10','您的人才信息注册申请已被驳回');
            }else{
                $message->addMessage($data['uid'],'10','您的人才信息注册申请审核不通过');
            }
            return response()->json(['code' => '1', 'message' => '审核成功']);
        } else {
            return response()->json(['code' => '0', 'message' => '审核失败']);
        }
    }


    /**
     * 验证
     * @param $data
     * @return array
     */
    public function getValidator($data)
    {
        $validator = \Validator::make($data, [
            'uid' => 'required|integer',
            'is_check' => 'required|integer|max:10',
            //'remark' => 'required',
        ], [
            'required' => ':attribute为必填项',
            'max' => ':attribute长度不符合要求',
            'integer' => ':attribute必须为数字',
        ], [
            'mobile' => '用户id',
            'is_check' => '审核结果',
            //'remark' => '备注',
        ]);


        //验证失败，并返回第一个报错
        if ($validator->fails()) {
            return ['code' => 0, 'message' => $validator->errors()->first()];
        }

        if($data['is_check'] != 1){
            if(empty($data['remark'])){
                return ['code'=>'0','message'=>'原因不能为空'];
            }

            //判断是否是审核不通过
            if($data['is_check'] == 3){
                if(empty($data['freeze_time'])){
                    return ['code'=>'0','message'=>'过期天数必须大于0'];
                }elseif (!is_int($data['freeze_time'])){
                    return ['code'=>'0','message'=>'过期天数必须大于0的整数'];
                }else{
                    if($data['freeze_time'] <= 0){
                        return ['code'=>'0','message'=>'过期天数必须大于0'];
                    }
                    $temp['is_freeze'] = 1;
                    $temp['freeze_time'] = strtotime("+".$data['freeze_time']." days",strtotime(date('Y-m-d',time())));
                }
            }
        }else{
            if(empty($data['remark'])){
                $data['remark'] = '';
            }
        }

        $talents_info = $this->memberTalentsModel->getTalents(['uid' => $data['uid']]);
        if (empty($talents_info)) {
            return ['code' => '0', 'message' => '请选择用户'];
        }

        if ($talents_info->is_check != 2) {
            return ['code' => '0', 'message' => '此申请您不能审核'];
        }

        if ($data['is_check'] == 1) {
            $temp['is_check'] = 1;
        } elseif ($data['is_check'] == 2) {
            $temp['is_check'] = 3;
        } elseif ($data['is_check'] == 3) {
            $temp['is_check'] = 4;
        }

        $temp['remark'] = $data['remark'];
        $temp['trial_user'] = $data['user']['uid'];
        $temp['trial_time'] = time();

        return ['code' => 1, 'message' => '验证成功', 'data' => $temp];
    }


    public function getUserZige(Request $request)
    {
        if (!$request->has('uid')) {
            return response()->json(['code' => '0', 'message' => '请上传用户uid']);
        }

        $dragon = $this->memberTalentsModel->getTalents(['uid' => $request->input('uid')]);
        if (empty($dragon)) {
            return response()->json(['code' => '0', 'message' => '该用户还为申请龙卡']);
        }
        if (empty($dragon->img)) {
            $img = [];
        } else {
            $img = json_decode($dragon->img, true);
        }
        return response()->json(['code' => '1', 'message' => '获取成功', 'data' => $img]);
    }


    public function getDetails(Request $request)
    {
        if (!$request->has('uid')) {
            return response()->json(['code' => '0', 'message' => '请上传用户uid']);
        }

        $member = $this->memberTalentsModel->getDetails($request->input('uid'));
        return response()->json(['code' => '1', 'message' => '获取成功', 'data' => $member]);
    }

    public function addTalents(Request $request)
    {
        $data = $request->input();
        if(empty($data['is_update'])){
            return response()->json(['code'=>'0','message'=>'请上传接口类型']);
        }
        $talents = new TalentsInfoController();
        $bool_data = $talents->getValidator($data,1);
        if($bool_data['code'] == 0){
            $result['code'] = '0';
            $result['message'] = $bool_data['message'];
            return response()->json($result);
        }

        $memberModel = new Member();
        $member = $memberModel->getMember(['mobile'=>$data['mobile']],['id','mobile']);
        if(empty($member)){
            $temp['mobile'] = $bool_data['data']['mobile'];
            $temp['name'] = $bool_data['data']['name'];
            $temp['user_id'] = $bool_data['data']['user']['uid'];
            $member = $memberModel->create($temp);
            if(empty($member)){
                return response()->json(['code'=>'0','message'=>'添加失败']);
            }
        }

        $talents_info = $this->memberTalentsModel->getTalents(['uid'=>$member->id]);
        if(!empty($talents_info)){
            if($data['is_update'] == 2){
                if($talents_info->is_check != 4){
                    return response()->json(['code'=>'0','message'=>'接口请求错误']);
                }elseif ($talents_info->freeze_time > time()){
                    return response()->json(['code'=>'0','message'=>'冻结时间未到，您不能修改']);
                }
            }
        }

        $bool_data['data']['user']['uid'] = $member->id;


        $bool_data['data']['user_id'] = $bool_data['data']['user']['uid'];
        $bool = $this->memberTalentsModel->addTalents($bool_data['data']);
        if($bool['code'] == 1){
            $message = new MessageController();
            $message->addMessage($member->id,'9','会员人才信息注册申请待审核',['is_check'=>'2']);
        }
        return response()->json($bool);
    }

    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function removeTalents(Request $request)
    {
        if(!$request->has('uid')){
            return response()->json(['code'=>'0','message'=>'请上传用户id']);
        }
        $uid = $request->input('uid');
        $member = $this->memberTalentsModel->where('uid',$uid)->where('user_id','>','0')->where('is_check','2')->first(['uid']);
        if(empty($member)){
            return response()->json(['code'=>'0','message'=>'该用户不能删除']);
        }

        if($this->memberTalentsModel->where('uid',$uid)->delete()){
            return response()->json(['code'=>'1','message'=>'删除成功']);
        }else{
            return response()->json(['code'=>'0','message'=>'删除失败']);
        }
    }


    /**
     * 批量导入
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bulkImport(Request $request)
    {
        if(!$request->has('excel')){
            $result = [
                'code' => '0',
                'message' => '请上传excel表格',
            ];
            return response()->json($result);
        }

        $file = $request->file('excel');
        if(!$file->isValid()){
            $result = [
                'code' => '0',
                'message' => '上传失败',
            ];
            return response()->json($result);
        }

        //扩展名
        $ext = $file->getClientOriginalExtension();
        if(!in_array($ext,['xls','xlsx'])){
            $result = [
                'code' => '0',
                'message' => '格式错误',
            ];
            return response()->json($result);
        }


        $user = $request->input();
        try{
            Excel::import(new MemberTalentsImports($user),$request->file('excel'));
        }catch (\Exception $e){
            return response()->json(['code'=>0,'message'=>$e->getMessage()]);
        }

        $result = [
            'code' => '1',
            'message' => '操作成功',
        ];
        return response()->json($result);
    }


    public function getMemberTalentsExcel()
    {
        $tanles = $this->memberTalentsModel->get();
        $temp['0'] = [
            '单位名称',
            '单位区域',
            '单位性质',
            '所属领域',
            '人才类别',
            '荣誉内容',
            '荣誉等级',
            '真实姓名',
            '联系电话',
            '身份证号码',
            '性别',
            '生日',
            '民族',
            '籍贯',
            '社保参保地',
            '来区工作时间',
            '学历',
            '学位',
            '职称',
            '现任职务',
            '详细地址',
            '居住区域',
            '学习与工作经历',
            '状态',
        ];




        $dragon = new DragonController();
        $basice_type = $dragon->basiceType();

        foreach ($tanles as $key=>$value){
            $keys = $key + 1;
            $temp[$keys]['enterprise_name'] = $value->enterprise_name;
            $temp[$keys]['area_range'] = $value->area_range;
            $temp[$keys]['nature_unit'] = $basice_type['nature_unit'][$value->nature_unit];
            $temp[$keys]['firm_name'] = $value->firm_name;
            $temp[$keys]['talents_type'] = $basice_type['talents_type'][$value->talents_type];
            $temp[$keys]['honor_content'] = $value->honor_content;
            $temp[$keys]['honor_grade'] = $value->honor_grade;
            $temp[$keys]['name'] = $value->name;
            $temp[$keys]['mobile'] = ' '.$value->mobile;
            $temp[$keys]['identity_num'] = ' '.(string)$value->identity_num;



            if($value->sex == 1){
                $temp[$keys]['sex'] = '男';
            }else{
                $temp[$keys]['sex'] = '女';
            }

            $temp[$keys]['birthday'] = $value->birthday;
            $temp[$keys]['mingzu'] = $value->mingzu;
            $temp[$keys]['birthplace'] = $value->birthplace;
            $temp[$keys]['social_security_address'] = $value->social_security_address;
            $temp[$keys]['come_district_time'] = $value->come_district_time;
            $temp[$keys]['xueli'] = $basice_type['xueli'][$value->xueli];
            $temp[$keys]['xuewei'] = $basice_type['xuewei'][$value->xuewei];
            $temp[$keys]['technical_level'] = $value->technical_level;
            $temp[$keys]['duty'] = $value->duty;
            $temp[$keys]['jz_address'] = $value->jz_address;
            $temp[$keys]['jz_area_range'] = $value->jz_area_range;
            $temp[$keys]['personal_experience'] = $value->personal_experience;


            if($value->is_check == 1){
                $temp[$keys]['is_check'] = '审核通过';
            }elseif ($value->is_check  == 2){
                $temp[$keys]['is_check'] = '待审核';
            }elseif ($value->is_check  == 3){
                $temp[$keys]['is_check'] = '驳回';
            }elseif ($value->is_check  == 4){
                $temp[$keys]['is_check'] = '不通过';
            }
        }


        $export = new MemberTalentsExport($temp);

        $name = '人才信息'.date('Y-m-d H:i:s');
        $download =  Excel::download($export,$name.'.xls');
        $file = $download->getFile();

        $upload = new ImageController();
        $path = $upload->getTypePath(3);

        if($path['code'] == 0){
            $result = [
                'code' => '0',
                'message' => '文件上传路径有误',
            ];
            return response()->json($result);
        }

        $pathName = $path['path'].$name.'.xls';
        $aly = $upload->AliyunOss($pathName,file_get_contents($file->getRealPath()));
        if($aly['info']['http_code'] != 200){
            return response()->json([
                'message'=>'上传失败',
                'code'=>'0',
            ]);
        }

        $result['code'] = '1';
        $result['message'] = '获取成功';
        $result['path'] = $aly['oss-request-url'];
        return response()->json($result);
    }
}
